//
//  SearchResultViewController.swift
//  Hermes
//
//  Created by FH on 2021/5/19.
//  Copyright © 2021 Agora. All rights reserved.
//

import Foundation

protocol SearchResultContext {
    var dataSource: PropState<[AstNode]> { get }
    func selectItem(_ item: AstNode)
}

class SearchResultViewController : NSViewController {
    var table: FLTableView<AstNode, SearchParamRowCellView>! = nil
    var properties: SearchResultContext! = nil
    var yoga: FLContext! = nil
    var superView: NSView! = nil
    var presentSize: CGSize? = nil
    
    convenience init(_ properties: SearchResultContext, presentSize: CGSize?) {
        self.init()
        self.properties = properties
        self.presentSize = presentSize
        if self.presentSize != nil {
            self.yoga = FLContext()
        }
    }
    
    override func loadView() {
        if let presentSize = self.presentSize {
            self.view = NSView(frame: CGRect(x: 0, y: 0, width: presentSize.width, height: presentSize.height))
            self.superView = self.view
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dataBinding()
        self.layoutViews()
    }
    
    func dataBinding() {
        self.properties.dataSource.signal().subscribeNext {[weak self] data in
            if let self = self, let table = self.table {
                table.reload(columnData: nil, rowData: data)
            }
        }
    }
    
    func layoutViews() {
        if self.yoga != nil {
            self.view.bindAsRoot(to: yoga)
            
            let dataSource = self.properties.dataSource.wrappedValue
            self.table = buildRowCellTableView(yoga, SearchParamRowCellView.self, data: dataSource)
            self.table.bind(to: yoga, self.view) { it in
                it.flexGrow = 1
            }
            yoga.apply()
        }
    }
    
    func layoutViews(yoga: FLContext, _ superView: NSView) {
        self.yoga = yoga
        self.superView = superView
        self.dataBinding()
        
        let dataSource = self.properties.dataSource.wrappedValue
        self.table = buildRowCellTableView(yoga, SearchParamRowCellView.self, data: dataSource)
        self.table.bind(to: yoga, self.superView) { it in
            it.flexGrow = 1
        }
        
        self.table.rac_eventSelectItem.subscribeNext {[weak self] (item, _) in
            if let self = self {
                self.properties.selectItem(item)
            }
        }
    }
}
